<!-- pages/Login.vue -->
<template>
  <div class="login">
    <div class="header">
      <router-link to="/" class="back-home">回到首页</router-link>
    </div>
    <div class="login-form">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="account">账号</label>
          <input type="account" id="account" v-model="account" required />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <div class="password-input">
            <input :type="showPassword ? 'text' : 'password'" id="password" v-model="password" required />
            <el-icon @click="togglePasswordVisibility" class="password-icon">
              <View />
            </el-icon>
          </div>
        </div>
        <div class="form-group captcha-group">
          <label for="code">验证码</label>
          <div class="captcha-input">
            <input type="text" id="code" v-model="code" required />
            <img :src="captchaImage" @click="refreshCaptcha" alt="验证码" class="captcha-image" />
          </div>
        </div>
        <button type="submit">登录</button>
        <p class="register-link">
          还没有账号？<router-link to="/register">注册</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { View } from '@element-plus/icons-vue';
import axios from 'axios';


const router = useRouter();

const account = ref('');
const password = ref('');

const code = ref('');
const uuid = ref('');
const captchaImage = ref('');

const showPassword = ref(false); // 控制密码是否显示

// 切换密码显示/隐藏
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};
// 获取验证码
const refreshCaptcha = async () => {
  try {
    const response = await axios.get('/api/captchaImage');
    if (response.data.code === 200) {
      captchaImage.value = `data:image/jpeg;base64,${response.data.img}`; // 设置验证码图片
      uuid.value = response.data.uuid; // 存储验证码的唯一标识
    } else {
      console.error('获取验证码失败:', response.data.msg);
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
};

// 初始化时获取验证码
onMounted(() => {
  refreshCaptcha();
});


const handleLogin = async () => {
  try {
    const response = await axios.post('/api/login', {
      username: account.value,
      password: password.value,
      code: code.value, // 如果需要验证码，填写验证码
      uuid: uuid.value  // 如果需要验证码，填写验证码的唯一标识
    });

    console.log('后端响应:', response.data); // 打印后端返回的数据

    if (response.data.code === 200) { // 根据后端返回的 code 判断登录是否成功
      // 存储 token
      localStorage.setItem('token', response.data.token);

      // 调用 getInfo 接口获取用户信息
      const userInfoResponse = await axios.get('/api/getInfo', {
        headers: {
          Authorization: `Bearer ${response.data.token}` // 携带 token
        }
      });

      // 存储用户昵称到 localStorage
      if (userInfoResponse.data && userInfoResponse.data.user) {
        localStorage.setItem('nickName', userInfoResponse.data.user.nickName || '用户');
        localStorage.setItem('avatar', userInfoResponse.data.user.avatar || '用户头像');
        localStorage.setItem('userId', userInfoResponse.data.user.userId || '用户Id');
        localStorage.setItem('userName', userInfoResponse.data.user.userName); // 假设登录接口返回用户账号
      }
      localStorage.setItem('isLoggedIn', 'true');

      // 登录成功，跳转到首页
      router.push('/');
    } else {
      // 登录失败，显示错误信息
      alert(response.data.msg || '登录失败，请检查账号和密码');
    }
  } catch (error) {
    console.error('登录失败:', error);
    alert('登录失败，请稍后重试');
  }
};
</script>

<style scoped lang="less">
.login {
  display: flex;
  flex-direction: column;
  /* 设置为列方向 */
  align-items: center;
  justify-content: center;
  /* 顶部对齐 */
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/login-bg.svg') no-repeat center center fixed;
  background-size: cover;
}

.header {
  width: 100%;
  padding: 10px 20px;
  position: absolute;
  /* 绝对定位 */
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
  /* 确保在表单之上 */
}

.back-home {
  color: #007bff;
  text-decoration: none;
  font-size: 16px;
  font-weight: bold;
}

.back-home:hover {
  text-decoration: underline;
}

.login-form {
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 300px;
  text-align: center;
}

h2 {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  text-align: left;
}

.password-input {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}

.password-input input {
  border: none;
  outline: none;
  padding: 8px;
}

.password-icon {
  cursor: pointer;
  color: #909399;
  margin-left: 10px;
}

.password-icon:hover {
  color: #409eff;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #0056b3;
}

.register-link {
  margin-top: 15px;
  font-size: 14px;
}

.register-link a {
  color: #007bff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

.captcha-group {
  margin-bottom: 15px;
}

.captcha-input {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 输入框和图片之间的间距 */
}

.captcha-image {
  width: 100px;
  /* 验证码图片宽度 */
  height: 40px;
  /* 验证码图片高度 */
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
